<?php

namespace App\Services\Site;

use App\Models\Site;
use App\Models\User;
use Illuminate\Contracts\Container\BindingResolutionException;
use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException;
use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException;

/**
 * 站点服务
 * @package App\Services
 */
class SiteService
{
    /**
     * 缓存站点
     * @param Site|null $site
     * @return null|Site
     */
    public function cache(Site $site = null)
    {
        static $cache = null;
        if ($site) {
            $cache = $site;
            $this->config($site);
        }
        return $cache;
    }

    /**
     * 站点配置项
     * @return void
     * @throws BindingResolutionException
     */
    public function config(Site $site)
    {
        //应用名
        config(['app.name' => $site['title']]);
        //站点配置
        config(['site' => $site['config']]);
        //邮箱配置
        config(['mail.mailers.smtp' => config('site.email')]);
        config(['mail.from.address' => config('site.email.username')]);
        config(['mail.from.name' => $site['title']]);
    }

    /**
     * 根据域名获取站点
     * @return exit
     * @throws BindingResolutionException
     * @throws SuspiciousOperationException
     * @throws ConflictingHeadersException
     */
    public function getByDomain()
    {
        $host = parse_url(request()->url())['host'];
        return Site::where('domain', 'like', "%{$host}%")->first();
    }


}
